package web.interceptor;

import java.io.BufferedReader;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.plugin.ehcache.CacheKit;

import exception.OpensnsException;
import kit.token.SnsSigCheck;
import web.common.ErrorCode;

/**
 * @ClassName: MessageInterceptor
 * @Description: jwt统一连接器
 * @author yyw
 * @date 2015年9月7日 上午1:55:22
 * 
 */
public class AuthInterceptor implements Interceptor {

	public void intercept(Invocation ai) {
		Controller controller=ai.getController();
		HttpServletRequest request = controller.getRequest();


		HashMap<String, String> params = requestParamsToMap(request);
		String sig = params.get("sig");
		String appid = (String) params.get("appid");
		if (StringUtils.isBlank(appid)) {
			controller.renderJson(
					"{\"status\":" + ErrorCode.PARAMETER_EMPTY + ",\"msg\":\"Request Doesn't has appid .\"}");
		} else if (StringUtils.isBlank(sig)) {
			controller.renderJson(
					"{\"status\":" + ErrorCode.PARAMETER_EMPTY + ",\"msg\":\"Request Doesn't has sig .\"}");
		} else {
			// TODO:从api川村中取出
			CacheKit.put("auth", "123456", "228bf094169a40a3bd188ba37ebe8723");
			String appkey = CacheKit.get("auth", appid);
			if (StringUtils.isNotBlank(appkey)) {
				try {
					boolean res = SnsSigCheck.verifySig(request.getMethod(), request.getRequestURI(), params,
							appkey, sig);
					if (res) {
						ai.invoke();
					} else {
						controller.renderJson("{\"status\":" + ErrorCode.RESPONSE_DATA_INVALID
								+ ",\"msg\":\"RESPONSE DATA INVALID .\"}");
					}
				} catch (OpensnsException e) {
					e.printStackTrace();
					controller.renderJson("{\"status\":" + e.getErrorCode() + ",\"msg\":\"verifySig Error .\"}");
				}
			} else {
				controller.renderJson("{\"status\":" + ErrorCode.PARAMETER_INVALID
						+ ",\"msg\":\"Request Doesn't has appid INVALID.\"}");
			}
		}
	

	}

	public static HashMap getBody(HttpServletRequest request) {

		StringBuffer jb = new StringBuffer();
		String line = null;
		try {
			BufferedReader reader = request.getReader();
			while ((line = reader.readLine()) != null)
				jb.append(line);
		} catch (Exception e) {
			/* report an error */ }
		String[] array = StringUtils.split(jb.toString(), "&");
		HashMap<String, String> map = new HashMap<>();
		for (String param : array) {

		}
		HashMap jsonObject = JSON.parseObject(jb.toString(), HashMap.class);
		return jsonObject;
	}

	public HashMap requestParamsToMap(ServletRequest req) {
		HashMap jsonObj = new HashMap<>();
		Map<String, String[]> params = req.getParameterMap();
		for (Map.Entry<String, String[]> entry : params.entrySet()) {
			String v[] = entry.getValue();
			Object o = (v.length == 1) ? v[0] : v;
			jsonObj.put(entry.getKey(), o);
		}
		return jsonObj;
	}
}
